package com.act;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.UploadPicBean;
import com.common.Constant;
import com.control.UserControl;
import com.xike.kyt.R;
import com.mUI.MyProgressDialog;
import com.mUI.MyUploadingDialog;
import com.upload.pic.Bimp;
import com.upload.pic.FileUtils;
import com.upload.pic.UploadConstant;
import com.upload.pic.UploadSelectPhotoAct;
import com.upload.pic.UploadUtils;
import com.xike.util.Manager;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class AnswerAct extends BaseAct implements OnClickListener {

	TextView tv_back, tv_publish;
	EditText edt_content;
	long questionId;

	String strCameraPhotoName;
	int uploadNum = 0;
	String strEdtContent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_answer);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			if (bundle.containsKey("questionId")) {
				questionId = bundle.getLong("questionId");
			}
		}
		initViews();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == UploadConstant.INTENT_REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
			if (Bimp.drr.size() < 9) {
				Bimp.drr.add(strCameraPhotoName);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void initViews() {
		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		tv_back.setOnClickListener(this);
		tv_publish = (TextView) findViewById(R.id.answer_tv_publish);
		tv_publish.setOnClickListener(this);

		edt_content = (EditText) findViewById(R.id.answer_edt_content);

		findViewById(R.id.answer_img_choseImage).setOnClickListener(this);

	}

	@Override
	protected void updateViews() {
	}

	private void serviceAnswer() {
		MyProgressDialog.show(this, true);
		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SERVICEDATA_ERROR:
					MyProgressDialog.cancle();
					mToast.showToast(AnswerAct.this, getString(R.string.net_error));
					break;
				case MSG_SERVICEDATA_OK:
					MyProgressDialog.cancle();
					BaseBean result = (BaseBean) msg.obj;
					if (result.isResult()) {
						mToast.showToast(AnswerAct.this, "发布成功");
						// UserControl.setUserInfoChanged(true);
						setResult(1);
						finish();
					} else {
						mToast.showToast(AnswerAct.this, result.getError_description());
					}
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}

		};
		Manager.singleThread.execute(new Runnable() {

			@Override
			public void run() {
				ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("access_token", UserControl.getAccessToken()));
				params.add(new BasicNameValuePair("app_key", Constant.APPKEY));
				params.add(new BasicNameValuePair("client_info", Manager.getClientInfo()));
				String strSignature = StringUtil.MD5(Constant.APPSERRET + UserControl.getAccessTokenSecret());
				params.add(new BasicNameValuePair("signature", strSignature));

				params.add(new BasicNameValuePair("question_id", String.valueOf(questionId)));
				params.add(new BasicNameValuePair("content", strEdtContent));

				params.add(new BasicNameValuePair("sign", MyUtil.getSignRequestParams(params)));

				BaseBean result = client.postFilesContent(Constant.SERVER_URL_QUESTION_ANSWER, null, params);
				Message msg = new Message();
				msg.what = MSG_SERVICEDATA_ERROR;
				if (result != null) {
					msg.what = MSG_SERVICEDATA_OK;
					msg.obj = result;
				}
				handler.sendMessage(msg);

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.answer_tv_publish:
			if (checkContent()) {
				serviceAnswer();
			}
			break;
		case R.id.headTitle_tv_back:
			finish();
			break;
		case R.id.answer_img_choseImage:
			toSelectPhotos();
			break;
		default:
			break;
		}
	}

	/**
	 * @Description: TODO<将选择的图片添加到edittext中>
	 * @author: wzl
	 * @data: 2014年11月4日 下午3:06:53
	 */
	private void addPicToEditText(String imgUrl, Bitmap bitmap) {
		Editable editable = edt_content.getEditableText();
		if(StringUtil.isNotNull(edt_content.getText().toString())){
			editable.append("\n");
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<img src=\"");
		sb.append(imgUrl);
		sb.append("\"/>");

		ImageSpan imageSpan = new ImageSpan(bitmap);
		SpannableString ss = new SpannableString(sb.toString());
		ss.setSpan(imageSpan, 0, sb.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


		int currentCursor = editable.length();
		editable.insert(currentCursor, ss);

		editable.append("\n");
	}

	/**
	 * @Description: TODO<去选择图片>
	 * @author: wzl
	 * @data: 2014年11月4日 下午3:07:23
	 */
	private void toSelectPhotos() {
		final MyUploadingDialog mDialog = new MyUploadingDialog(AnswerAct.this);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.show();
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes();
		lp.width = (int) (display.getWidth()); // 设置宽度
		mDialog.getWindow().setAttributes(lp);
		mDialog.setOnBtnPhotoClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(AnswerAct.this, UploadSelectPhotoAct.class);
				startActivity(intent);
				mDialog.dismiss();
			}
		});
		mDialog.setOnBtnTakePic(new OnClickListener() {

			@Override
			public void onClick(View v) {
				strCameraPhotoName = Manager.getCACHE_IMAGE_DIR() + System.currentTimeMillis() + "_temp.jpg";
				UploadUtils.openCameraAndSavePhoto(strCameraPhotoName, AnswerAct.this, UploadConstant.INTENT_REQUEST_CODE_CAMERA);
				mDialog.dismiss();
			}
		});
	}

	/**
	 * @Description: TODO<处理选择的图片>
	 * @author: wzl
	 * @data: 2014年11月4日 下午3:07:42
	 */
	private void dealSelectPhotos() {
		if (Bimp.drr.size() <= 0) {
			return;
		}
		MyProgressDialog.show(this, true);
		for (int i = 0; i < Bimp.drr.size(); i++) {
			uploadNum++;
			try {
				String path = Bimp.drr.get(Bimp.max);
				Bitmap bm = Bimp.revisionImageSize(path);
				Bimp.bmp.add(bm);
				String newStr = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
				FileUtils.saveBitmap(bm, "" + newStr);
				Bimp.max += 1;
				serviceUploadPic(path, bm);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Description: TODO<上传图片>
	 * @author: wzl
	 * @data: 2014年11月4日 下午3:08:07
	 */
	private void serviceUploadPic(final String bitmapPath, final Bitmap bitmap_up) {
		final Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (uploadNum == Bimp.drr.size()) {
					MyProgressDialog.cancle();
					Bimp.clearPics();
					uploadNum = 0;
				}

				switch (msg.what) {
				case MSG_SERVICEDATA_ERROR:
					mToast.showToast(AnswerAct.this, getString(R.string.net_error));
					break;
				case MSG_SERVICEDATA_OK:
					UploadPicBean result = (UploadPicBean) msg.obj;
					if (result.isReturnTrue()) {
						String returnUrl = result.getUrl();
						if (StringUtil.isNotNull(returnUrl)) {
							addPicToEditText(returnUrl, bitmap_up);
						}

					} else {
						mToast.showToast(AnswerAct.this, result.getError_description());
					}

					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}

		};
		Manager.singleThread.execute(new Runnable() {

			@Override
			public void run() {
				ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("access_token", UserControl.getAccessToken()));
				params.add(new BasicNameValuePair("app_key", Constant.APPKEY));
				params.add(new BasicNameValuePair("client_info", Manager.getClientInfo()));
				String strSignature = StringUtil.MD5(Constant.APPSERRET + UserControl.getAccessTokenSecret());
				params.add(new BasicNameValuePair("signature", strSignature));

				params.add(new BasicNameValuePair("sign", MyUtil.getSignRequestParams(params)));

				String strResult = client.postFileContent(Constant.SERVER_URL_UPLOAD_PICTURE, bitmapPath, params);
				UploadPicBean result = gson.fromJson(strResult, UploadPicBean.class);
				Message msg = new Message();
				msg.what = MSG_SERVICEDATA_ERROR;
				if (result != null) {
					msg.what = MSG_SERVICEDATA_OK;
					msg.obj = result;
				}
				handler.sendMessage(msg);

			}
		});

	}

	private boolean checkContent() {
		String strContent = MyUtil.getEditTextContent(edt_content);
		if (!StringUtil.isNotNull(strContent)) {
			mToast.showToast(this, "回答内容不能为空");
			return false;
		}
		strEdtContent = "<p>" + strContent + "</p>";
		strEdtContent = strEdtContent.replaceAll("\n", "</p><p>");

		Log.e("checkContent:", "" + strEdtContent);
		return true;
	}

	protected void onRestart() {
		dealSelectPhotos();
		super.onRestart();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			Bimp.clearPics();
		}
		return super.dispatchKeyEvent(event);
	}

}
